//
//  OAuthViewController.swift
//  WeiboTest
//
//  Created by 张文文 on 15/5/13.
//  Copyright (c) 2015年 zww. All rights reserved.
//

import UIKit
import SVProgressHUD

class OAuthViewController: UIViewController, UIWebViewDelegate {

    //申请应用时分配的AppKey
    let WB_Client_Id = "2526720857"
    //授权回调地址
    let WB_Redirect_Uri = "http://www.baidu.com"
    //申请应用时分配的AppSecret
    let WB_Client_Secret = "568f5726f6191a449c89a5647016c3e1"
    
    //计算属性 只有getter   Readonly
    var webView:UIWebView {
        return view as! UIWebView
    }
    
    //关闭当前页面
    @IBAction func close(sender: AnyObject) {
        dismissViewControllerAnimated(true, completion: nil)
        
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        
    }
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        loadAuthPath()
    }
    
    /**
     加载授权界面
    */
    private func loadAuthPath() {
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=" + WB_Client_Id + "&redirect_uri=" + WB_Redirect_Uri
        let url = NSURL(string: urlString)
        webView.loadRequest(NSURLRequest(URL: url!))
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    /**
   
    1> https://api.weibo.com/ 继续加载
    2> 授权成功 回调地址开头 https://www.baidu.com/?code=61eb1adbb78ab0525048f1fd4ff8c1fe
    3> http://m.weibo.cn/reg/index     影响用户体验
    4> http://login.sina.com.cn/sso/   影响用户体验
    5> 用户取消授权 http://www.baidu.com/?error_uri=%
    
    分析：
    1> 如果 URL 以 https://api.weibo.com/ 开头就继续加载页面
    2> 如果 URL 以 http://www.baidu.com 开头，不用加载页面
    - 判断是否有 code，就是请求码
    3> 其他页面统一不加载
    */

    
    // MARK: - UIWebViewDelegate代理方法
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        println(request.URL)
        //去的URL的完整字符串
        let urlString = request.URL!.absoluteString!
        //1.如果是官方的页面就继续加载
        if urlString.hasPrefix("https://api.weibo.com/") {
            return true
        }
        //2.判断url是否是设置的回调地址
        if !urlString.hasPrefix(WB_Redirect_Uri) {
            return false
        }
        //3.代码执行到这里，就一定是回调函数
        //query可以过滤掉主机名和协议头
        println("==========" + request.URL!.query!)
        
        let query = request.URL!.query! as NSString
        let codeStr = "code="
        if query.hasPrefix(codeStr){
            //获取请求码
            let code = query.substringFromIndex(codeStr.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))
            println("验证码 " + code)
            //获取 AccessToken
            loadAccessToken(code)
        
            
            
        } else {
            println("用户拒绝")
            SVProgressHUD.dismiss()
            dismissViewControllerAnimated(true, completion: nil)
        }
      
        return false
    }
    
    private func loadAccessToken(code: String) {
        let params = ["client_id": WB_Client_Id,
            "client_secret": WB_Client_Secret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": WB_Redirect_Uri
        ]
        UserAccount.loadAccessToken(params)
    }
    
    //开始加载页面
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    //页面加载完成
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }


}
